<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

/*
 代理微信绑定
api/home/bindwechat.tsl
参数：
wechatid：微信ID
phonenum：手机号码
password：登录密码

*/
class User extends Controller{
	
    public function index(){
		
		$request = Request::instance();
		
		//首次进入带参数清理wechat_id
		$clear = $request->param('clear');
		if($clear == '1'){
			Session::delete('wechat_id');
		}
		
		//①得到wechat_id
		if(!IS_TEST){
			//当前登陆状态
			if(!Session::has('wechat_id')){
				$this->wxlogin();
				exit();
			}
		}else{
			//测试
			Session::set('wechat_id','oRDpMt8FvPrZ6gbwoWerEc_5mI_80005');
		}

		//显示页面
		defined('WECHAT_ID') or define('WECHAT_ID',Session::get('wechat_id'));
		
		return view('');
    }
	
	
	//执行绑定
	public function bindwechat(){
		$req = Request::instance();
		if($req->isPost()){
			
			if(!Session::has('wechat_id')){
				ajax('操作失败');
			}
			defined('WECHAT_ID') or define('WECHAT_ID',Session::get('wechat_id'));
			
			$phonenum = $req->param('phonenum');
			if(!\RegexHelper::is_phone($phonenum)){
				ajax('手机号码输入有误');
			}
			
			$loginpwd1 = $req->param('loginpwd1');
			$loginpwd2 = $req->param('loginpwd2');
			if($loginpwd1 == '' || $loginpwd1 !== $loginpwd2){
				ajax('登陆密码输入错误');
			}
			
			$pm = [
				'wechatid' => WECHAT_ID,
				'password' => $loginpwd1,
				'phonenum' => $phonenum,
			];
			$res = \ServerHelper::post('^/home/bindwechat',$pm);
			$data = $this->J($res);
			
			if(empty($data['flag'])){
				ajax($data['msg']);
			}
			ajax($data['msg'],true);
		}
	}
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			__log($list,'welogin');
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
	private function wxlogin(){
		if(!__iswechat()){
			$this->error('请在微信中登陆');
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('登录：没有设置微信appid','weixin');
			$this->error('系统错误');
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('User/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('登录：没有设置微信appid或appsecret','weixin');
			$this->error('系统错误');
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			$this->error('登录发起失败');
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			$this->error('登陆发起失败');
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			$this->error('登陆发起失败');
		}
		
		//第四步：拉取用户信息(需scope为 snsapi_userinfo)
		$access_token = $info['access_token'];
		$openid = $info['openid'];
		$url = "https://api.weixin.qq.com/sns/userinfo";
		$url.= "?access_token=$access_token&openid=$openid&lang=zh_CN";
		$info = $this->getJson($url);
		if(!isset($info['openid'])){
			$this->error('登陆发起失败');
		}
		
		Session::set('wechat_id',$info['openid']);
		$this->redirect('User/index');
	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}

}
